<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

  <form action="demo/save" method="post" name="form1">
    <input name="username" required >
    <input name="password" type="password">
<!--    <input type="submit" value="提交">-->
    <button id="btn">提交</button>
<!--    <button type="submit">提交</button>-->
<!--    <button type="button"  id="btn">普通</button>-->
  </form>

  <hr />
  <button>普通按钮</button>

<script>
  var btn = document.querySelector("#btn");
  btn.onclick = function(event){
      // 阻止表单提交
      event.preventDefault();

    // var form = document.querySelector("form");
    // 表单提交, 响应结果会直接显示在浏览器中。网页会刷新
    // form.submit();

    // 异步请求. XmlHttpRequest, fetch, axios.js, jquery ajax。响应结果不会直接显示在浏览器中。网页不会刷新
    fetch("demo/save", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
          "username": 'aaa',
          'password': 'bbb'
      })
    }).then(function(response){
      return response.json();
    }).then(function(data){
      console.log(data);
      if (data.code == 200){
        alert("保存成功");
      } else {
        alert(data.msg);
      }
    });

    // 表单不提交
    // return false;
  }
</script>
</body>
</html>